# -*- coding:utf-8 -*-
# @FileName :logging.py
# @Date: 2023/7/6
# @Author:天空之城

import logging
import os
import datetime
import inspect


class Logger:
    class CustomFilter(logging.Filter):
        def filter(self, record):
            # 获取记录日志时调用堆栈的帧列表
            frame_list = inspect.stack()

            # 查找记录日志的帧
            for frame in frame_list:
                # 确保跳过 logger 类和 logging 模块自身的帧
                if frame.filename == __file__ or frame.filename.endswith('/logging/__init__.py'):
                    continue

                # 找到第一个不属于 logger 类和 logging 模块的帧，即为记录日志的调用帧
                record.filename = os.path.basename(frame.filename)  # 只获取文件名
                record.lineno = frame.lineno
                break

            return True

    @staticmethod
    def get_log_file_path(log_folder_path, log_file_name):
        today = datetime.datetime.now().strftime('%Y-%m-%d')
        log_file_name = str(log_file_name).replace('.log', f'_{today}.log')
        log_file_path = os.path.join(log_folder_path, log_file_name)
        return log_file_path

    def __init__(self, log_folder_path, log_file_name, log_encode='UTF-8'):
        # 确保日志目录存在
        if not os.path.exists(log_folder_path):
            os.makedirs(log_folder_path)

        # 构建日志文件路径
        log_file_path = self.get_log_file_path(log_folder_path, log_file_name)

        # 初始化日志编码和日志文件路径
        self.__log_encode = log_encode
        self.__log_file_path = log_file_path

        # 创建logger对象并设置日志级别
        self._logger = logging.getLogger(log_file_name)
        self._logger.setLevel(logging.DEBUG)

        # 创建日志格式
        formatter = logging.Formatter(
            '%(asctime)s - %(filename)s - %(levelname)s - %(funcName)s - %(lineno)d - %(message)s')

        # 创建文件处理器并添加到logger
        file_handler = logging.FileHandler(log_file_path, encoding=log_encode)
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)
        self._logger.addHandler(file_handler)

        # 创建控制台处理器并添加到logger
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.DEBUG)
        console_handler.setFormatter(formatter)
        self._logger.addHandler(console_handler)

        # 添加自定义过滤器
        custom_filter = self.CustomFilter()
        self._logger.addFilter(custom_filter)

    def debug(self, message):
        self._logger.debug(message)

    def info(self, message):
        self._logger.info(message)

    def warning(self, message):
        self._logger.warning(message)

    def error(self, message):
        self._logger.error(message)

    def critical(self, message):
        self._logger.critical(message)
